import React, { Component } from 'react';
import {
    View,
    Dimensions,
    StyleSheet,
    ScrollView,
    Alert,
    TouchableWithoutFeedback,
    TouchableHighlight,
    DeviceEventEmitter,
    Platform,
    Image
} from 'react-native';
import { Container, Content, Button, Icon, Text, List, ListItem, Body, Spinner } from 'native-base';
import Accordion from 'react-native-collapsible/Accordion';
import Collapsible from 'react-native-collapsible';
import { NavigationActions } from 'react-navigation';
import { connect } from 'react-redux';
import course from '../../net/course';
import URL from '../../net/url.js';
import interaction from '../../net/interaction.js';
import ChapterInfo from '../../db/coursedb/chapter_unit_table.js';
const { width, height } = Dimensions.get('window');
const color = Platform.OS === 'ios' ? '#1C82FB' : '#1A1A1A';
const text = Platform.OS === 'ios' ? '' : '';
class study_course_information extends Component {
    static navigationOptions = ({ navigation }) => ({
        title: navigation.state.params.title,
        //headerBackTitle:'课程中心',
        headerLeft: (
            <List style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }}>
                <Icon name="arrow-back"
                    style={{ paddingLeft: 15, fontSize: 25, opacity: 0.9, color: color }}
                    onPress={() => {
                        const resetAction = NavigationActions.reset({
                            index: 0,
                            actions: [
                                NavigationActions.navigate({ routeName: 'MainTab' })
                            ],
                        })
                        navigation.dispatch(resetAction);
                    }}
                />
                <Text style={{ fontSize: 15, color: color }}>{text}</Text>
            </List>
        )
    });
    constructor(props) {
        super(props);
        this.state = {
            selectedItem: -1,
            courseinfo: null,
            chapterTitle: null,
            //学生端签到
            sign: '签到',
            //教师端上课
            courseIcon: '上课'
        }
    }
    async componentWillMount() {
        let Interaction = new interaction();
        const { course_info } = this.props;
        const { login_info_role } = this.props;
        if (login_info_role.customRole == 'teacher') {
            this.subscription = DeviceEventEmitter.addListener('classIconDidChange', (events) => {
                this.setState({ courseIcon: '下课' });
                DeviceEventEmitter.emit('classStatus');
            });
            let OnlineClassStatus = await Interaction.CheckOnlineClassIcon(course_info.courseid);
            if (OnlineClassStatus == 0) {
                this.setState({
                    courseIcon: '下课',
                });
            }
        } else {
            let InteractionCourseID = await Interaction.getInteractionCourseID(course_info.courseid);
            if (InteractionCourseID != undefined) {
                let SignInIconStatus = await Interaction.studentCheckSignInIconStatus(course_info.courseid, login_info_role.userName);
                if (SignInIconStatus.errorCode == 0) { this.setState({ sign: '已签到', }) }
            }
        }

        //章节信息缓存
        let chapterIn = new ChapterInfo();
        try {
            await chapterIn.createChapterInfoTable();
            let info = await chapterIn.queryChapterInfo(course_info.courseid);
            if (info != null && info.length > 0) {
                console.log('chapterIn1111111111');
                let outArray = JSON.parse(info.item(0).chaptervalue);
                this.setState({ courseinfo: outArray });
                await chapterIn.closeChapterInfo();

            } else {
                console.log('chapterIn2222222222');
                let cs = new course();
                let outArray = await cs.get_course_info(course_info.courseid);
                this.setState({ courseinfo: outArray });
                chapterIn.insertChapterInfo(course_info.courseid, JSON.stringify(outArray));
                await chapterIn.closeChapterInfo();
            }
        } catch (e) {
            console.log("error", e);
        }
    }
    componentWillUnmount() {
        // 移除
        const { login_info_role } = this.props;
        if (login_info_role.customRole == 'teacher') { this.subscription.remove(); }
    }

    render_content(l) {
        const { setChapterId } = this.props;
        return l.map((v, i) => {
            return (
                <View key={i}>
                    <ListItem button style={StyleSheet.flatten(styles.menuList)}
                        onPress={() => {
                            this.setState(this.state.selectedItem != i ? { selectedItem: i } : { selectedItem: -1 });
                            this.setState({ chapterTitle: v.title });
                        }}>
                        <Body>
                            <Text style={StyleSheet.flatten(styles.textStyle)}>{v.title}</Text>
                        </Body>
                    </ListItem>

                    <Collapsible collapsed={this.state.selectedItem === i ? false : true}>
                        <List>
                            {v.moduleList.map((v, j) => {
                                return (
                                    <ListItem key={j} style={StyleSheet.flatten(styles.subList)}
                                        onPress={() => {
                                            setChapterId({
                                                type: 'GetChapterIdSuccess',
                                                payload: {
                                                    subChapterTitle: v.title,
                                                    subChapterId: v.id,
                                                    chapterTitle: this.state.chapterTitle
                                                }
                                            });
                                            //this.props.navigation.dispatch('CourseDetail');
                                            this.props.navigation.navigate('CourseDetail');

                                        }}>
                                        <Icon name='md-book' style={{ opacity: 0.5, color: '#62B1F6', paddingRight: 5 }} />
                                        {/* <Icon name='md-book' style={{ opacity: 0.5, color: '#1ae', paddingRight: 5 }} /> */}
                                        <Body>
                                            <Text style={StyleSheet.flatten(styles.subtextStyle)}>{v.title}</Text>
                                        </Body>
                                        <Icon name="arrow-forward" style={{ opacity: 0.5, color: '#62B1F6' }} />
                                        {/* <Image style={StyleSheet.flatten(styles.backIcon)} source={require('../../images/back.png')} /> */}
                                    </ListItem>
                                );
                            })}
                        </List>
                    </Collapsible>
                </View>
            );
        })
    }

    renderLoadingView() {
        return (
            <Container>
                <Content>
                    <Spinner color='green' />
                </Content>
            </Container>
        );
    }

    render() {
        const { navigate } = this.props.navigation;
        const { login_info_role } = this.props;
        const { course_info } = this.props;
        if (!this.state.courseinfo) {
            return this.renderLoadingView();
        }
        if (login_info_role.customRole == 'teacher') {
            return (
                <Container style={StyleSheet.flatten(styles.Container)}>
                    <ListItem itemDivider><Text style={StyleSheet.flatten(styles.title)}>课程工具</Text></ListItem>
                    <View style={styles.twoIcon}>
                        <TouchableWithoutFeedback onPress={() => { this.courseIcon_onPress(); }} >
                            <View style={styles.Icon1} >
                                <Icon name="notifications" style={{ color: '#28AB91' }} />
                                {/* <Icon name="ios-hand-outline" style={{color:'#5CB85C'}}/> */}
                                <Text style={StyleSheet.flatten(styles.textStyle)}>{this.state.courseIcon}</Text>
                            </View>
                        </TouchableWithoutFeedback>
                        <TouchableWithoutFeedback onPress={() => { this.interaction_onPress_teacher(course_info.courseid, course_info.coursetitle, navigate) }} >
                            <View style={styles.Icon23}>
                                <Icon name="sync" style={{ color: '#F0AD4E' }} />
                                {/* <Icon name="ios-shuffle" style={{color:'#D9534F'}}/> */}
                                <Text style={StyleSheet.flatten(styles.textStyle)}>交互</Text>
                            </View>
                            {/* <Button info>
                                <Icon name="ios-shuffle"  />
                                <Text>交互</Text>
                            </Button> */}
                        </TouchableWithoutFeedback>
                        <TouchableWithoutFeedback onPress={() => {
                            this.props.navigation.navigate('CourseTools', { title: this.props.navigation.state.params.title, classStatus: this.state.courseIcon });
                        }} >
                            <View style={styles.Icon23}>
                                <Icon name="add" style={{ color: '#D9534F' }} />
                                {/*  */}
                                <Text style={StyleSheet.flatten(styles.textStyle)}>更多</Text>
                            </View>
                        </TouchableWithoutFeedback>
                    </View>
                    <Content >
                        <ListItem itemDivider><Text style={StyleSheet.flatten(styles.title)}>课程章节</Text></ListItem>
                        <ScrollView ref={(scrollView) => { _scrollView = scrollView; }} style={StyleSheet.flatten(styles.ScrollView)}>
                            {this.render_content(this.state.courseinfo)}
                        </ScrollView>
                    </Content>
                </Container>
            );

        }
        return (
            <Container style={StyleSheet.flatten(styles.Container)}>
                <ListItem itemDivider><Text style={StyleSheet.flatten(styles.title)}>课程工具</Text></ListItem>
                <View style={styles.twoIcon}>
                    <TouchableWithoutFeedback onPress={() => { this.studentSignIn(); }} >
                        <View style={styles.Icon1} button>
                            <Icon name="notifications" style={{ color: '#28AB91' }} />
                            <Text style={StyleSheet.flatten(styles.textStyle)}>{this.state.sign}</Text>
                        </View>
                    </TouchableWithoutFeedback>
                    <TouchableWithoutFeedback onPress={() => { this.interaction_onPress_student(course_info.courseid, course_info.coursetitle, navigate) }}>
                        <View style={styles.Icon23}>
                            <Icon name="sync" onPress={this.onPressButton} style={{ color: '#F0AD4E' }} />
                            {/* <Icon name="ios-shuffle" onPress={this.onPressButton} style={{color:'#D9534F'}}/> */}
                            <Text style={StyleSheet.flatten(styles.textStyle)}>交互</Text>
                        </View>
                    </TouchableWithoutFeedback>
                </View>
                <ListItem itemDivider><Text style={StyleSheet.flatten(styles.title)}>课程章节</Text></ListItem>
                <Content >
                    <ScrollView ref={(scrollView) => { _scrollView = scrollView; }} style={StyleSheet.flatten(styles.ScrollView)}>
                        {this.render_content(this.state.courseinfo)}
                    </ScrollView>
                </Content>
            </Container>
        );
    }
    //上课按钮单击事件（上课，下课两种图标，处在不同图标单击操作事件不同）
    async courseIcon_onPress() {
        const { course_info } = this.props;
        let Interaction = new interaction();
        console.log('moocCourseID', course_info.courseid)
        if (this.state.courseIcon == '上课') {
            let InteractionCourseID = await Interaction.getInteractionCourseID(course_info.courseid);
            if (InteractionCourseID != undefined) { this.props.navigation.navigate('ClassList_Course', { title: this.props.navigation.state.params.title }); }
            else { Alert.alert('温馨提醒:', '此课程未非交互课程'); }
        }
        else {
            let closeCourseResult = await Interaction.closeCourse(course_info.courseid);
            console.log('关闭课堂', closeCourseResult)
            if (closeCourseResult == 0) {
                this.setState({ courseIcon: '上课' });
                Alert.alert('温馨提醒:', '关闭课堂成功');
            }
            else {
                Alert.alert('温馨提醒:', '关闭课堂失败');
            }
        }
    }
    // 课程-交互-单击事件（学生端）  
    async interaction_onPress_student(courseid, coursetitle, navigate) {
        const { course_info } = this.props;
        const { InteractionPushSubjectId } = this.props;
        let Interaction = new interaction();
        let OnlineClassID_InteractionCourseID_Result = await Interaction.get_OnlineClassIDSubjectIDSendSubjectID_Student(courseid);
        console.log('学生端交互')
        console.log(OnlineClassID_InteractionCourseID_Result)
        console.log(OnlineClassID_InteractionCourseID_Result.messageInfo)
        let messageInfo = OnlineClassID_InteractionCourseID_Result.messageInfo;
        if (OnlineClassID_InteractionCourseID_Result.errorCode == 0) {
            InteractionPushSubjectId({
                type: 'InteractionPushSubjectId',
                payload: {
                    //推送题目id
                    subjectId: messageInfo[0].SubjectID,
                    //上课号，学生端提交答案使用
                    OnlineClassID: messageInfo[0].OnlineClassID,
                    //题目推送号
                    SendSubjectID: messageInfo[0].SendSubjectID,
                }
            });
            navigate('QuestionStudent_course', { title: coursetitle, type: 'course' })
            // Alert.alert('温馨提醒:', messageInfo);
        } else if (OnlineClassID_InteractionCourseID_Result.errorCode == 1) {
            if (messageInfo == 'subject closed') { Alert.alert('温馨提醒:', '此课堂题目已关闭'); }
            else if (messageInfo == 'no subject') { Alert.alert('温馨提醒:', '此课堂暂无推送题目'); }
            else if (messageInfo == 'Course Closed') { Alert.alert('温馨提醒:', '课堂未开启'); }
            else if (messageInfo == 'not interactionCourse') { Alert.alert('温馨提醒:', '此课程为非交互课程'); }
        }


    }
    // 课程-交互-单击事件（教师端） 
    async interaction_onPress_teacher(courseid, coursetitle, navigate) {
        const { InteractionPush_OnlineClassID_interactionCourseID } = this.props;
        let Interaction = new interaction();
        let OnlineClassID_InteractionCourseID_Result = await Interaction.getOnlineClassID_InteractionCourseID(courseid);
        console.log('教师端-交互-单击事件-OnlineClassID_InteractionCourseID_Result')
        console.log(OnlineClassID_InteractionCourseID_Result)
        if (OnlineClassID_InteractionCourseID_Result.errorCode == 0) {
            //Alert.alert('温馨提醒:', 'resultData.messageInfo');
            let messageInfo = OnlineClassID_InteractionCourseID_Result.messageInfo;
            InteractionPush_OnlineClassID_interactionCourseID({
                type: 'Get_InteractionCourseId_OnlineClassID',
                payload: {
                    //交互课程id
                    interactionCourseID: messageInfo[0].interactionCourseID,
                    //上课号，用户获取答题结果及发布消息体发送
                    OnlineClassID: messageInfo[0].OnlineClassID,
                }
            });
            this.props.navigation.dispatch('CourseQuestionList');
            navigate('CourseQuestionList', { title: coursetitle, type: 'course' });
        } else if (OnlineClassID_InteractionCourseID_Result.errorCode == 1) {
            if (OnlineClassID_InteractionCourseID_Result.messageInfo == 'Course Closed') {
                Alert.alert('温馨提醒:', '课堂未开启');
            }
            else if (resultData.messageInfo == 'not interactionCourse') {
                Alert.alert('温馨提醒:', '此课程未非交互课程');
            }
        }
    }
    // 课程-学生端签到单击事件 
    async studentSignIn() {
        const { course_info } = this.props;
        const { login_info_role } = this.props;
        console.log('course_info.courseid')
        console.log(course_info.courseid)
        console.log('login_info_role.userName')
        console.log(login_info_role.userName)
        let Interaction = new interaction();
        let CurrentPosition = await Interaction.getCurrentPosition();
        let studentSignInResult = await Interaction.studentSignIn(course_info.courseid, login_info_role.userName, login_info_role.realName, CurrentPosition.longitude, CurrentPosition.latitude);
        console.log('学生端签到studentSignInResult' + studentSignInResult)
        if (studentSignInResult.errorCode == 0) {
            Alert.alert('温馨提醒:', '签到成功');
            this.setState({ sign: '已签到', })
        } else {
            if (studentSignInResult.messageInfo == 'SignIn Closed' || studentSignInResult.messageInfo == 'SignIn has not been opened') {
                console.log('储相瑞java')
                Alert.alert('温馨提醒:', '签到未开启');
            }
            else if (studentSignInResult.messageInfo == 'Course Closed' || studentSignInResult.messageInfo == 'The Course has not been opened') {
                Alert.alert('温馨提醒:', '课堂未开启');
            }
            else if (studentSignInResult.messageInfo == 'SignIn Again') {
                Alert.alert('温馨提醒:', '不允许重复签到');
            }
            else if (studentSignInResult.messageInfo == 'not InteractionCourse') {
                Alert.alert('温馨提醒:', '此课程为非交互课程');
            }

        }

    }

}

const styles = StyleSheet.create({

    menuList: {
        marginRight: 0,
        marginLeft: 0,
        marginTop: 1,
        paddingTop: 12,
        paddingBottom: 12,
        paddingLeft: 10,
        paddingRight: 10,
        backgroundColor: 'white',
        borderBottomWidth: 0.2,
        borderBottomColor: "#cac0c0",
    },
    subList: {
        marginRight: 0,
        marginLeft: 0,
        paddingTop: 10,
        paddingBottom: 10,
        paddingLeft: 30,
        paddingRight: 20,
        backgroundColor: 'white',
        borderBottomWidth: 0.2,
        borderBottomColor: "#cac0c0",
    },
    twoIcon: {
        flexDirection: 'row',
        backgroundColor: 'white',
    },
    Icon1: {
        paddingLeft: 35,
        paddingTop: 10,
        paddingRight: 20,
        paddingBottom: 10,
        alignItems: 'center',
        alignSelf: 'center',
    },
    Icon23: {
        paddingLeft: 15,
        paddingTop: 10,
        paddingBottom: 10,
        paddingRight: 20,
        alignItems: 'center',
        alignSelf: 'center',
    },
    title: {
        fontSize: 17,
        color: '#353535',
    },
    textStyle: {
        fontSize: 16,
        color: '#353535',
    },
    subtextStyle: {
        fontSize: 14,
        color: '#62B1F6'//'#353535',

    },
    ScrollView: {
        height: 480,
    },
    Container: {
        marginTop: 0,
        backgroundColor: '#fff'
    },
    backIcon: {
        width: 20,
        height: 20,
        // marginLeft:'63%',
        marginRight: '5%',
        opacity: 0.6,

    },

}
);
function mapStateToProps(state) {
    return {
        course_info: state.course_info.course_info,
        login_info_role: state.login.login_info
    }
}

function mapDispatchToProps(dispatch) {
    return {
        setChapterId: (state) => dispatch(state),
        InteractionPush_OnlineClassID_interactionCourseID: (state) => dispatch(state),
        InteractionPushSubjectId: (state) => dispatch(state),
    }
}

const PageStudyCourseInfo = connect(
    mapStateToProps,
    mapDispatchToProps
)(study_course_information)
export default PageStudyCourseInfo;